package mylab.starters.cloud.feign;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.experimental.UtilityClass;
import mylab.base.constants.Const;
import org.slf4j.MDC;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 链路追踪工具类
 *
 * @author xuzhanfu
 */
@UtilityClass
public class TraceUtil {

    /**
     * 从header和参数中获取traceId
     * 从前端传入数据
     *
     * @param request 　HttpServletRequest
     * @return traceId
     */
    public String getTraceId(HttpServletRequest request) {
        String traceId = request.getParameter(Const.HTTP_REQUEST_TRACE_ID);
        if (CharSequenceUtil.isBlank(traceId)) {
            traceId = request.getHeader(Const.HTTP_REQUEST_TRACE_ID);
        }
        return traceId;
    }

    /**
     * 传递traceId至MDC
     *
     * @param traceId 　跟踪ID
     */
    public void mdcTraceId(String traceId) {
        if (CharSequenceUtil.isNotBlank(traceId)) {
            MDC.put(Const.LOG_TRACE_ID, traceId);
        }
    }
}
